package config

import (
	"errors"
	"os/user"
	"path"
	"time"
)

var ProxyInfo = &Proxy{}

type Proxy struct {
	Host                 string
	Port                 int
	User                 string
	Password             string
	Key                  string
	KeyPassphrase        string
	BastionHost          string
	BastionPort          int
	BastionUser          string
	BastionPassword      string
	BastionKey           string
	BastionKeyPassphrase string
	ConnectTimeout       time.Duration
	LocalAddress         string
	RemoteAddress        string
	Protocol             string
	Type                 string
}

func (p *Proxy) Parse() error {
	// 获取运行用户
	if p.User == "" {
		currenUser, err := user.Current()
		if err != nil {
			return err
		}
		p.User = currenUser.Username
	}
	// 读取ssh key
	if p.Password == "" {
		if p.Key == "~/.ssh/id_rsa" {
			currenUser, err := user.Current()
			if err != nil {
				return err
			}
			p.Key = path.Join(currenUser.HomeDir, ".ssh/id_rsa")
		}
		key, err := readSSHKey(p.Key)
		if err != nil {
			return err
		}
		p.Key = key
	} else {
		p.Key = ""
	}
	// 校验转发类型
	if p.Type != "local" && p.Type != "remote" {
		return errors.New("proxy type is one of [local, remote]")
	}
	// 如果不存在跳板机
	if p.BastionHost == "" {
		return nil
	}
	if p.BastionUser == "" {
		p.BastionUser = p.User
	}
	if p.BastionPassword == "" {
		if p.BastionKey == "~/.ssh/id_rsa" {
			currenUser, err := user.Current()
			if err != nil {
				return err
			}
			p.BastionKey = path.Join(currenUser.HomeDir, ".ssh/id_rsa")
		}
		key, err := readSSHKey(p.BastionKey)
		if err != nil {
			return err
		}
		p.BastionKey = key
	} else {
		p.BastionKey = ""
	}

	return nil
}
